<?php
/**
 * Created by PhpStorm.
 * User: Zhang Ligang
 * Date: 2016/8/16
 * Time: 9:39
 */


class Export
{
    public static function exportToExcel(PHPExcel $phpExcel, $title, $dataHead, $dataBody)
    {
        $phpExcel->getProperties()->setCreator("Short Perton")
            ->setLastModifiedBy("Short Perton")
            ->setTitle($title)
            ->setSubject("Excel 导出工具")
            ->setDescription("可用于 Office 2007 XLSX 的 Excel 导出工具, 使用 PHP 类生成.")
            ->setKeywords("导出文档")
            ->setCategory("导出示例");

        // Add some data
        foreach ($dataHead as $key => $head) {
            $s = chr($key+65);
            $phpExcel->setActiveSheetIndex(0)->setCellValue($s.'1', $head);
        }
        foreach ($dataBody as $key => $body) {
            $d = $key +2;
            foreach ($body as $k => $value) {
                $s = chr($k+65);
                $phpExcel->setActiveSheetIndex(0)->setCellValue($s.$d, $value);
            }
        }

        $phpExcel->setActiveSheetIndex(0);

        // Redirect output to a client’s web browser (Excel5)
        $filename = date('Y_m_d_His', time()) . rand(1000, 9999) . '.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header("Content-Type:application/force-download");
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0

        $objWriter = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

}